<?php  
	session_start();
	
	/* Error messages to inform user */
	$MSG_ChangePwd = "";
	$MSG_CreateSession = "";
	$MSG_deleteData = "";
	
	/* Used for communication with the database */
	require_once("classes/Mail.class.php");
	include("classes/database.class.php");
	include("includes/define.php");
	$bd = new Database(MYSQL_DB_HOST,MYSQL_DB_LOGIN,MYSQL_DB_PASSWORD,MYSQL_DB_NAME);
	
	date_default_timezone_set('Europe/Paris');
	$today = date("Y")."-".date("m")."-".date("d");

	/* If someone try to go directly to this URL, redirect to index */
	if(!$_SESSION['admin'])
	{
		header("Location: http://".$_SERVER['SERVER_NAME']);
	}
	/* Deconnection */
	if(isset($_POST['logout']))
	{
		session_destroy();
		header("Location: http://".$_SERVER['SERVER_NAME']);
	}
	/* Create a new Session for a study starting */
	elseif(isset($_POST['newSession']))
	{	
		/* Tests if the date is well-formed */
		if (preg_match("([0-9]{2}[/][0-9]{2}[/][0-9]{4})", $_POST['dateSession'], $matches))
		{
			/* Format it to SQL format date */
			$_POST['dateSession'] = preg_replace("/(\d+)\/(\d+)\/(\d+)/", "$3-$2-$1", $_POST['dateSession']);
		}
		/* Tests if the date is well-formed */
		if(preg_match("([0-9]{4}[-][0-9]{2}[-][0-9]{2})", $_POST['dateSession'], $matches))
		{
			if($_POST['dateSession'] >= $today)
			{
				if(isset($_POST['induction']))
				{
					$bd->query("INSERT INTO sessions (sessionId, date, induction, studyId) VALUES ('".base_convert(time(),10,36)."', '".$_POST['dateSession']."','".$_POST['induction']."', '".$_SESSION['studyId']."');");
					$bd->close();
				}
				else { $MSG_CreateSession = "<p class='error'>Il faut choisir une induction pour la session.</p>"; }
			}
			else { $MSG_CreateSession = "<p class='error'>La date choisie est passée, elle ne peut donc pas être utilisée pour la création de session.</p>"; }
		}
		else { $MSG_CreateSession = "<p class='error'>La date n'est pas syntaxiquement correcte, elle doit être de la forme : JJ/MM/AAAA.</p>"; }
	}
	/* Admin want to change his password */
	elseif(isset($_POST['changePassword']))
	{
		$jsonID = json_decode(file_get_contents("logs.json"),true);
		if(md5($_POST['oldPassword']) == $jsonID['password'])
		{	
			if($_POST['newPassword'] == $_POST['confirmPassword'])
			{
				if(strlen($_POST['newPassword'])>= 4)
				{
					$jsonID['password']=md5($_POST['newPassword']);
					file_put_contents("logs.json",json_encode($jsonID));
					$MSG_ChangePwd = "<p>Le mot de passe a été changé.</p>";
				}
				else { $MSG_ChangePwd = "<p class='error'>Le mot de passe doit avoir une longueur de 4 caractères minimum.</p>"; }
			}
			else { $MSG_ChangePwd = "<p class='error'>Erreur à la confirmation du mot de passe.</p>" ; }
		}
		else { $MSG_ChangePwd = "<p class='error'>L'ancien mot de passe est erroné.</p>" ; }
	}
	/* Admin want to obtains results of all studies */
	elseif(isset($_POST['results']))
	{
		require_once("classes/ArrayToCSV.class.php");
		require_once("classes/DataManager.class.php");
		$dm = new DataManager();
		$headers = $dm->makeHeaders();
		
		$atcsv = new ArrayToCSV("Resultats.csv",$headers,$dm->makeValues());
		$atcsv->exportToCSV();
	}
	/* Start new study */
	elseif(isset($_POST['startStudy']))
	{	
		$bd->query("INSERT INTO studies (beginDate) VALUES ('".$today."') ;");
		$bd->close();
	}
	/* Stop the study starting */
	elseif(isset($_POST['stopStudy']))
	{
		$bd->query("UPDATE studies SET endDate = '".$today."' WHERE endDate IS NULL; ");
		$bd->close();
	}
	/* Delete data of a participant */
	elseif(isset($_POST['deleteData']))
	{
		$DATABASE_participantExist = $bd->query("SELECT * FROM participants WHERE participantId = '".$_POST['participantId']."';");
		if(mysql_num_rows($DATABASE_participantExist)==0)
		{
			$MSG_deleteData = "<p class='error'>Aucun participant ne correspond à cet identifiant.</p>";
		}
		else
		{
			$DATABASE_participantSessions = $bd->query("SELECT * FROM participantsSessions WHERE participantId = '".$_POST['participantId']."';");
			if(mysql_num_rows($DATABASE_participantSessions) != 0)
			{
				while($DATABASE_participantSession = mysql_fetch_assoc($DATABASE_participantSessions))
				{
					$bd->query("DELETE FROM panasAnswers WHERE participantSessionId = '".$DATABASE_participantSession['participantSessionId']."';");
					$bd->query("DELETE FROM colorAnswers WHERE participantSessionId = '".$DATABASE_participantSession['participantSessionId']."';");
				}
				$bd->query("DELETE FROM participantsSessions WHERE participantId = '".$_POST['participantId']."';");
				$MSG_deleteData = "<p>Les données ont été supprimées.</p>";
			}
			else { $MSG_deleteData = "<p class='error'>Il n'y a aucune donnée à supprimer.</p>"; }
		}
	}
	
	/* Test if a study is starting or no */
	$DATABASE_isStarting = $bd->query("SELECT * FROM studies WHERE endDate IS NULL;");
	$bd->close();
	$DATABASE_isStudyStarting = mysql_fetch_assoc($DATABASE_isStarting);
	if(mysql_num_rows($DATABASE_isStarting)==0) { if(isset($_SESSION['studyId'])){unset($_SESSION['studyId']);} }
	else { $_SESSION['studyId'] = $DATABASE_isStudyStarting['studyId'];}
?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
<title> Panneau d'administration </title>
</head>

<body>
	<div id="admin">
		<div class="admin">
			<h1> Administrateur </h1>
			
			<form method="post" action="admin.php">
				<input type="submit" name="logout" value="Déconnexion"/>
			</form>
			
			<br/>
			<hr/>
			<br/>
			
			<form method="post" action="admin.php">
				<input id="oldPassword" name="oldPassword" type="password" placeholder="ancien mot de passe"/> <br/>
				<input id="newPassword" name="newPassword" type="password" placeholder="nouveau mot de passe"/> <br/>
				<input id="confirmPassword" name="confirmPassword" type="password" placeholder="confirmation du mot de passe"/> 
				
				<br/><br/>
				<input type="submit" name="changePassword" value="Changer de mot de passe" />
			</form>
			<?php echo $MSG_ChangePwd; ?>
			
			<br/>
			<hr/>
			<br/>
			
			<?php
				$DATABASE_isResult = $bd->query("SELECT * FROM participantsSessions;");
				$bd->close();
				if(mysql_num_rows($DATABASE_isResult) != 0)
				{
					echo "<form method='post' action='admin.php'>
							<input type='submit' name='results' value='Obtenir les résultats'/>
						</form>
							
						<br/>
						<hr/>
						<br/>";
				}
			?>
			
			<form method="post" onsubmit="return confirm('Etes-vous sur de vouloir supprimer ces données ?')" action="admin.php">
				<input type="text" name="participantId" placeholder="Id du participant"/>
				<input type="submit" name="deleteData" value="Supprimer ses données"/>
			</form>
			<?php echo $MSG_deleteData; ?>
		</div>
		
		<div class="admin"> 
			<?php
				if(isset($_SESSION['studyId']))
				{	
					$DATABASE_allStudies = $bd->query("SELECT * FROM sessions WHERE studyId = '".$_SESSION['studyId']."' ORDER BY date DESC;");
					$bd->close();
					if(mysql_num_rows($DATABASE_allStudies) > 0)
					{
						$DATABASE_beginDateStudy = $bd->query("SELECT beginDate FROM studies WHERE studyId = '".$_SESSION['studyId']."';");
						$bd->close();
						$beginDate = mysql_fetch_assoc($DATABASE_beginDateStudy);
						$beginDate = preg_replace("/(\d+)-(\d+)-(\d+)/", "$3/$2/$1", $beginDate['beginDate']);
						
						echo "<p>Session(s) pour l&#146;étude en cours (débutée le ".$beginDate." )</p>
								<table> <thead> <tr> <td>Date</td> <td>Induction</td> <td>Code</td> </tr> </thead> <tbody>";
						
						while($DATABASE_study = mysql_fetch_assoc($DATABASE_allStudies))
						{
							$userDate = preg_replace("/(\d+)-(\d+)-(\d+)/", "$3/$2/$1", $DATABASE_study['date']);
							echo "<tr> <td>".$userDate."</td><td>".$DATABASE_study['induction']."</td><td>".$DATABASE_study['sessionId']."</td></tr>";
						}
						echo "<tbody> </table>";
					}
					else
					{
						echo "<p> Aucune session n'a été enregistré pour cette étude </p>";
					}
					echo "<br/>
							<hr/>
							<br/>
							
							<form method='post' action='admin.php'>
							<label for='dateSession'>Date : </label><input id='dateSession' name='dateSession' type='date' placeholder='JJ/MM/AAAA'/> 
							<br/>
							<input type='radio' name='induction' value='-' id='negative'/><label for='negative'>I- (négatif)</label>
							<input type='radio' name='induction' value='+' id='positive'/><label for='positive'>I+ (positif)</label> 
							<input type='radio' name='induction' value='=' id='neutral'/><label for='neutral'>I= (neutre)</label>
							
							<br/><br/>
							<input type='submit' name='newSession' value='Créer une session de test' />
							".$MSG_CreateSession."
						</form>
						
						<br/>
						<hr/>
						<br/>
						
						<form method='post' onsubmit='return confirm(\"Etes-vous sur de vouloir arréter cette étude ?\")' action='admin.php'>
							<input type='submit' name='stopStudy' value='Arrêter l&#146;étude'/>
						</form>"; 
				}
				else
				{
					echo "<p> Il n'y a aucune étude en cours, veuillez en démarrer une afin de pouvoir créer une session. </p> 
							
						<br/>
						<hr/>
						<br/>
					
						<form method='post' action='admin.php'>
							<input type='submit' name='startStudy' value='Démarrer l&#146;étude'/>
						</form>";
				}
			?>	
			
			
			<?php
				$DATABASE_isStudy = $bd->query("SELECT * FROM studies;");
				if(mysql_num_rows($DATABASE_isStudy)!=0)
				{
					echo "<br/>
						<hr/>
						<br/>
							
						<form method='post' action='oldStudies.php'>
							<input type='submit' name='oldStudies' value='Voir toutes les études'/>
						</form>";
				}
			?>
		</div>
	</div>
	
</body>
</html>